<script>
	export default {
		globalData: {
			localSocket: {},
			callback: function() {}
		},
		onLaunch: async function (options) {
			console.log('App Launch');

			// #ifdef MP-QQ
			qq.showShareMenu({
				showShareItems: ['qq', 'qzone', 'wechatFriends', 'wechatMoment']
			});
			// #endif

			// H5环境检测
			// #ifdef H5
			this.$store.commit('app/setRunEnv', this.util.runEnv());
			// #endif

			if (options.query) {
				// 检查存在邀请码和渠道码记录下来
				if (options.query.inviteCode) {
					uni.setStorageSync('inviteCode', options.query.inviteCode);
				}
				if (options.query.channelName) {
					uni.setStorageSync('channelName', options.query.channelName);
				}
			}

			// 更新baseUrl
			this.$store.commit('app/setBaseUrl', this.util.baseUrl());

			// 清除所有Storge
			if (!this.$store.state.app.createTime || this.$store.state.app.createTime < 1582465098) {
				this.util.removeStorageSync('vuex');
				window.location.reload();
			}
			// 获取站点信息
			if (!this.$store.state.app.siteInfo.id) {
				this.getSiteInfo();
			}

			// 获取用户信息
			if (this.$store.state.user.token && this.$store.state.user.userInfo.id == 0) {
				await this.getUserInfo();
			}

			// 本地数据超过1800秒则更新
			if (Date.parse(new Date()) / 1000 - this.$store.state.app.updateTime > 1800) {
				await this.getSiteInfo();
				if (this.$store.state.user.token && this.$store.state.user.userInfo.id == 0) {
					await this.getUserInfo();
				}
				this.$store.commit('app/setData', { key: 'updateTime', value: Date.parse(new Date()) / 1000 });
			}

			// 设置iOS-Safari分发模式兼容
			// #ifdef H5
			// document.querySelector("meta[name=apple-mobile-web-app-title]").content = this.$store.state.app.siteInfo.title;
			// document.querySelector("link[rel=apple-touch-icon]").href = this.$store.state.app.siteInfo.logo;
			// #endif

			// #ifdef APP-PLUS||H5||MP-WEIXIN
			if (process.env.NODE_ENV == 'production') {
			    //this.initSocket(this.util.wsUrl());
			}

			// #endif
			// this.checkUpdate('/v1/cloud/index/appUpdate');
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods:{
			initSocket(url) {
				let that = this;

				that.globalData.localSocket = uni.connectSocket({
					// 小程序必须类似wss://echo.websocket.org/
					url: url + '?Authorization=' + this.util.getToken(),
					complete: ()=> {} // return a socketTask
				});
				// 版本库需要在 1.7.0 以上
				that.globalData.localSocket.onOpen(function(res) {
				  console.log('WebSocket连接已打开！readyState=' + that.globalData.localSocket._webSocket.readyState);
				})
				that.globalData.localSocket.onError(function(res) {
				  console.log('readyState=' + that.globalData.localSocket._webSocket.readyState);
				})
				that.globalData.localSocket.onClose(function(res) {
				  console.log('WebSocket连接已关闭！readyState=' + that.globalData.localSocket._webSocket.readyState);
				  that.initSocket();
				})
				that.globalData.localSocket.onMessage(function(res) {
				  // 用于在其他页面监听 websocket 返回的消息
				  that.globalData.callback(res);
				})
			},
			// 统一发送消息，可以在其他页面调用此方法发送消息
			sendSocketMessage: function(msg) {
				let that = this
				return new Promise((resolve, reject) => {
				  if (this.globalData.localSocket._webSocket.readyState === 1) {
					console.log('发送消息', msg)
					this.globalData.localSocket.send({
					  data: JSON.stringify(msg),
					  success: function(res) {
						resolve(res)
					  },
					  fail: function(e) {
						reject(e)
					  }
					})
				  } else {
					console.log('已断开')
				  }
				})
			},
			async getSiteInfo(){
				let res = await this.util.request({
					url: '/v1/cloud/index/info',
					method: 'get',
				});
				if (res.code == '200') {
					this.$store.commit('app/setSiteInfo', res.data.siteInfo)
				} else {
					this.util.showToast({
						title: res.msg,
						icon: 'loading',
						duration: 3000
					});
				}
			},
			async getUserInfo() {
				let res1 = await this.util.request({
					url: '/v1/core/user/info',
					method: 'get',
				});
				if (res1.code == '200') {
					var defaultUserInfo = this.$store.state.user.userInfo;
					for (let key in res1.data.userInfo) {
						if (res1.data.userInfo[key] != '') {
							defaultUserInfo[key] = res1.data.userInfo[key];
						}
					}
					this.$store.commit('user/setUserInfo', defaultUserInfo);
				} else {
					this.util.showToast({
						title: res1.msg,
						icon: 'loading',
						duration: 3000
					});
				}
			},
			checkUpdate(url){
				let _this = this;
				// #ifdef APP-PLUS
				// 锁定屏幕方向
				plus.screen.lockOrientation('portrait-primary'); //锁定
				// 热更新
				plus.runtime.getProperty(plus.runtime.appid, async function(widgetInfo) {
					let res = await _this.util.request({
						url: url,
						data: {
							version: widgetInfo.version,
							name: widgetInfo.name
						}
					});
					if (res.code == 200) {
						if (res.data.versionInfo.wgtUrl) {
							uni.downloadFile({
								url: res.data.versionInfo.wgtUrl,
								success: (downloadResult) => {
									if (downloadResult.statusCode === 200) {
										plus.runtime.install(downloadResult.tempFilePath, {
											force: false
										}, function() {
											console.log('install success...')
											plus.runtime.restart()
										}, function(e) {
											console.error('install fail...')
										})
									}
								}
							});
						} else {
							// 提醒用户更新
							uni.showModal({
								title: '更新提示',
								content: '是否选择更新',
								success: (ret) => {
									if (ret.confirm) {
										plus.runtime.openURL(res.data.versionInfo.appDownurl);
									}
								}
							})
						}
					}
				});
				// #endif
			}
		}
	}
</script>

<style lang="scss">
	/*
	 * 样式
	 */
	@import '@/components/xyui/src/xyui.scss';
	@import url("/components/gaoyia-parse/parse.css");
	/* input 样式 */
	.input-placeholder {
		color: #999999;
	}
	.placeholder {
		color: #999999;
	}
	/* 骨架屏替代方案 */
	.Skeleton {
		background: #f3f3f3;
		padding: 20upx 0;
		border-radius: 8upx;
	}
	/* 图片载入替代方案 */
	.image-wrapper {
		font-size: 0;
		background: #f3f3f3;
		border-radius: 4px;
		image {
			width: 100%;
			height: 100%;
			transition: .6s;
			opacity: 0;

			&.loaded {
				opacity: 1;
			}
		}
	}
	.common-hover {
		background: #f5f5f5;
	}
	
	view,
	scroll-view,
	swiper,
	swiper-item,
	cover-view,
	cover-image,
	icon,
	text,
	rich-text,
	progress,
	button,
	checkbox,
	form,
	input,
	label,
	radio,
	slider,
	switch,
	textarea,
	navigator,
	audio,
	camera,
	image,
	video {
		box-sizing: border-box;
	}
	/* 商品列表 */
	.item-list-section{
		margin-top: 10px;
		display:flex;
		flex-wrap:wrap;
		padding: 0 10px;
		.guess-item{
			background: #fff;
			margin-bottom: 10px;
			border-radius: 5px;
			display:flex;
			flex-direction: column;
			width: 48%;
			padding-bottom: 0px;
			&:nth-child(2n+1){
				margin-right: 4%;
			}
			.image-wrapper{
				width: 100%;
				height: 175px;
				overflow: hidden;
				padding: 0px;
				image{
					width: 100%;
					height: 100%;
					opacity: 1;
				}
			}
			.title{
				padding: 5px 5px;
				font-size: 13px;
				color: $font-color-dark;
				line-height: 18px;
			}
			.price{
				padding: 3px 5px;
				font-size: 14px;
				font-weight: 500;
				color: $uni-color-primary;
				line-height: 1.3;
			}
		}
	}
	
	/* 横向列表商品 */
	.goods-box {
		height: 160upx;
		padding: 20upx 0;
		white-space: nowrap;
		.goods-item {
			width: 160upx;
			height: 160upx;
			display: inline-block;
			margin-right: 24upx;
		}
		.goods-img {
			display: block;
			width: 100%;
			height: 100%;
		}
	}
	/* 竖向列表商品 */
	.goods-box-single {
		display: flex;
		padding: 20upx 0;
		.goods-img{
			display: block;
			width: 140upx;
			height: 140upx;
		}
		.right {
			flex: 1;
			display: flex;
			flex-direction: column;
			padding: 0 30upx 0 24upx;
			overflow: hidden;
			.title {
				font-size: $font-base + 2upx;
				color: $font-color-dark;
				line-height: 1;
			}
			.attr-box {
				display: flex;
				justify-content: space-between;
				font-size: $font-sm + 2upx;
				color: $font-color-light;
				padding: 10upx 0upx;
			}
			.price-box {
				display: flex;
				justify-content: space-between;
				.price {
					font-size: $font-base + 0upx;
					color: $font-color-dark;
					&:before{
						content: '￥';
						font-size: $font-sm;
						margin: 0 2upx 0 0upx;
					}
				}
			}
		}
	}
	.price-total{
		display: flex;
		justify-content: space-between;
		align-items: baseline;
		padding: 20upx 0upx;
		font-size: $font-sm + 2upx;
		color: $font-color-light;
		.time {}
		.summary {
			padding-right: 30upx;
			.num {
				margin: 0 8upx;
				color: $font-color-dark;
			}
			.price {
				font-size: $font-lg;
				color: $font-color-dark;
				&:before{
					content: '￥';
					font-size: $font-sm;
					margin: 0 2upx 0 8upx;
				}
			}
		}
	}
</style>
